/*\
 *  Copyright (C) 2005  Anthony Liguori <anthony@codemonkey.ws>
 *
 *  Network Block Device
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; under version 2 of the License.
 * 
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 * 
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
\*/

#include "bits.h"

size_t wr_sync(int fd, void *buffer, size_t size, bool do_read)
{
	size_t offset = 0;

	while (offset < size) {
		ssize_t len;

		if (do_read) {
			len = read(fd, buffer + offset, size - offset);
		} else {
			len = write(fd, buffer + offset, size - offset);
		}

		/* recoverable error */
		if (len == -1 && errno == EAGAIN) {
			continue;
		}

		/* eof */
		if (len == 0) {
			break;
		}

		/* unrecoverable error */
		if (len == -1) {
			return 0;
		}

		offset += len;
	}

	return offset;
}

int tcp_socket_outgoing(const char *address, uint16_t port)
{
	int s;
	struct in_addr in;
	struct sockaddr_in addr;
	int serrno;

	s = socket(PF_INET, SOCK_STREAM, 0);
	if (s == -1) {
		return -1;
	}

	if (inet_aton(address, &in) == 0) {
		struct hostent *ent;

		ent = gethostbyname(address);
		if (ent == NULL) {
			goto error;
		}

		memcpy(&in, ent->h_addr, sizeof(in));
	}

	addr.sin_family = AF_INET;
	addr.sin_port = htons(port);
	memcpy(&addr.sin_addr.s_addr, &in, sizeof(in));

	if (connect(s, (struct sockaddr *)&addr, sizeof(addr)) == -1) {
		goto error;
	}

	return s;
error:
	serrno = errno;
	close(s);
	errno = serrno;
	return -1;
}

int tcp_socket_incoming(const char *address, uint16_t port)
{
	int s;
	struct in_addr in;
	struct sockaddr_in addr;
	int serrno;
	int opt;

	s = socket(PF_INET, SOCK_STREAM, 0);
	if (s == -1) {
		return -1;
	}

	if (inet_aton(address, &in) == 0) {
		struct hostent *ent;

		ent = gethostbyname(address);
		if (ent == NULL) {
			goto error;
		}

		memcpy(&in, ent->h_addr, sizeof(in));
	}

	addr.sin_family = AF_INET;
	addr.sin_port = htons(port);
	memcpy(&addr.sin_addr.s_addr, &in, sizeof(in));

	opt = 1;
	if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)) == -1) {
		goto error;
	}

	if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) == -1) {
		goto error;
	}

	if (listen(s, 128) == -1) {
		goto error;
	}

	return s;
error:
	serrno = errno;
	close(s);
	errno = serrno;
	return -1;
}

